import fs from 'fs'
//文件路径
let BASE_DIR = '' // 所有文件生成到store/modules下
let apiFilePath = ``
let mutationsFilePath = ``
let actionsFilePath = ``
let mutationTypesFilePath = ``
let gettersFilePath = ``
//基本参数
let apiName = ''
let remark = ''
let apiUrl = ''
let requestType = ''
import { IStoreFilesParams } from '../common/types/file'
/**
 * 文件生成规则
 * **/
// 1. api写入
function addApiToFile() {
  let newApiName = apiName

  if (requestType == 'get') {
    //将apiName首字母大写，并前面拼接get
    newApiName = _firstUpperCase(apiName)
    newApiName = 'get' + newApiName
  }

  let isCorrect = _checkCorrect(apiFilePath, `export const ${newApiName} *= *['"].+['"]`, apiUrl)
  if (isCorrect) {
    const newApi = `
/**
 * ${remark}
 */
export const ${newApiName} = '${apiUrl}';\n`
    fs.appendFileSync(apiFilePath, newApi, 'utf8')
    console.log(`接口 ${newApiName} 添加成功`)

    return `接口 ${newApiName} 添加成功`
  }
  return `接口 ${newApiName} 添加失败`
}
// 2. mutation-types写入
function addMutationTypes() {
  let newApiName = apiName.toUpperCase()
  let isCorrect1 = _checkCorrect(
    mutationTypesFilePath,
    `export const ${newApiName + '_REQUEST'} *= *['"].+['"]`
  )
  let isCorrect2 = _checkCorrect(
    mutationTypesFilePath,
    `export const ${newApiName + '_RECEIVE'} *= *['"].+['"]`
  )

  if (isCorrect1 && isCorrect2) {
    let newApi = `
/**
 * ${remark}
 */
export const ${newApiName + '_REQUEST'} = '${newApiName + '_REQUEST'}';\n
export const ${newApiName + '_RECEIVE'} = '${newApiName + '_RECEIVE'}';\n`
    fs.appendFileSync(mutationTypesFilePath, newApi, 'utf8')
    console.log(`mutation-types ${newApiName} 添加成功`)
    return `mutation-types ${newApiName} 添加成功`
  }
  return `mutation-types ${newApiName} 添加失败`
}
//3. getters 写入
async function addGettersToFile() {
  // 1. 初始化文件（如果需要）
  if (!fs.existsSync(gettersFilePath)) {
    fs.writeFileSync(
      gettersFilePath,
      `
  export default { }
            `.trim(),
      'utf8'
    )
  }

  // 2. 读取最新内容（每次重新读取）
  let content = fs.readFileSync(gettersFilePath, 'utf8')
  // 3. 处理state
  const getterRegex = /export\s+default\s*{([^{}]*?(?:\{[^{}]*\}[^{}]*?)*)}/

  if (getterRegex.test(content)) {
    content = content.replace(getterRegex, (_, stateContent) => {
      if (new RegExp(`${apiName}Info\\s*:|${apiName}Status\\s*:`).test(stateContent)) {
        throw new Error(`State中已存在${apiName}相关属性`)
      }
      return `export default {
    ${stateContent.trim()}
    ${remark ? `// ${remark}` : ''}
    ${apiName}Info,
    ${apiName}Status,
}`
    })
  }
  // 创建内容导出
  let isCorrect1 = _checkCorrect(gettersFilePath, `const ${apiName + 'Info'} *= *['"].+['"]`)
  let isCorrect2 = _checkCorrect(gettersFilePath, `const ${apiName + 'Status'} *= *['"].+['"]`)
  if (isCorrect1 && isCorrect2) {
    let newApi = `
  /**
   * ${remark}
   */
  const ${apiName + 'Info'} = state =>state.${apiName + 'Info'}||{};\n
  const ${apiName + 'Status'} = state =>state.${apiName + 'Status'}||'';\n`

    newApi = newApi + content
    fs.writeFileSync(gettersFilePath, newApi, 'utf8')
    console.log(`getters ${apiName} 添加成功`)
    return `getters ${apiName} 添加成功`
  }
  return `getters ${apiName} 添加失败`
}
// 4. mutations 写入
function addMutationsToFile() {
  // 1. 初始化文件（如果需要）
  if (!fs.existsSync(mutationsFilePath)) {
    fs.writeFileSync(
      mutationsFilePath,
      `
import * as type from './mutation-types'
export const state = {}
export const mutations = {}
        `.trim(),
      'utf8'
    )
  }

  // 2. 读取最新内容（每次重新读取）
  let content = fs.readFileSync(mutationsFilePath, 'utf8')

  // 3. 处理state
  const stateRegex = /export\s+const\s+state\s*=\s*{([^{}]*?(?:\{[^{}]*\}[^{}]*?)*)}/ ///export\s+const\s+state\s*=//\s*{([\s\S]*?)}/;
  if (stateRegex.test(content)) {
    content = content.replace(stateRegex, (_, stateContent) => {
      if (new RegExp(`${apiName}Info\\s*:|${apiName}Status\\s*:`).test(stateContent)) {
        throw new Error(`State中已存在${apiName}相关属性`)
      }
      return `export const state = {
    ${stateContent.trim()}
    ${remark ? `// ${remark}` : ''}
    ${apiName}Info: {},
    ${apiName}Status: '',
}`
    })
  }

  // 4. 处理mutations（关键修正）
  const mutationRegex = /export\s+const\s+mutations\s*=\s*{([\s\S]*?)}\s*$/
  if (mutationRegex.test(content)) {
    content = content.replace(mutationRegex, (_, mutationContent) => {
      if (
        new RegExp(`\\[type\\.${apiName.toUpperCase()}_(REQUEST|RECEIVE)\\]`).test(mutationContent)
      ) {
        throw new Error(`Mutations中已存在${apiName}相关操作`)
      }
      return `export const mutations = {
    ${mutationContent.trim()}
    ${remark ? `// ${remark}` : ''}
    [type.${apiName.toUpperCase()}_REQUEST](state) {
        state.${apiName}Status = 'loading';
        state.${apiName}Info = {};
    },
    [type.${apiName.toUpperCase()}_RECEIVE](state, res) {
        state.${apiName}Status = 'loaded';
        state.${apiName}Info = res?.content || {};
    },
}`
    })
  }

  // 5. 写入最终结果
  fs.writeFileSync(mutationsFilePath, content, 'utf8')
  console.log(`${apiName}相关mutations配置已添加`)

  return `${apiName}相关mutations配置已添加`
}
//5. actions.js
function addActionsToFile() {
  // 1. 初始化文件（如果需要）
  if (!fs.existsSync(actionsFilePath)) {
    fs.writeFileSync(
      actionsFilePath,
      `
import * as type from './mutation-types'
import * as API from './api'
import { ajax } from '@/utils/fetch'
        `.trim(),
      'utf8'
    )
  }

  // 2. 读取最新内容（每次重新读取）
  let content = fs.readFileSync(actionsFilePath, 'utf8')
  // 3. 判断文件中是否存在函数名称为apiName的函数
  if (_checkFunctionExists(content, apiName)) {
    throw new Error(`函数 ${apiName} 已存在`)
  }
  let newApiName = apiName
  if (requestType == 'get') {
    //将apiName首字母大写，并前面拼接get
    newApiName = _firstUpperCase(apiName)
    newApiName = 'get' + newApiName
  }
  // 4. 追加新函数
  const newAction = `
${remark ? `// ${remark}` : ''}
export const ${newApiName} = ({ commit }, data) => {
    commit(type.${apiName.toUpperCase()}_REQUEST, data);
    return ajax.${requestType}(
        API.${newApiName},
        { commit },
        data,
        type.${apiName.toUpperCase()}_RECEIVE
    );
};`

  fs.appendFileSync(actionsFilePath, newAction, 'utf8')
  console.log(`${apiName}相关actions配置已添加`)
  return `${apiName}相关actions配置已添加`
}
function addIndexToFile() {
  if (!fs.existsSync(`${BASE_DIR}/index.js`)) {
    fs.writeFileSync(
      `${BASE_DIR}/index.js`,
      `
import { mutations, state } from './mutations.js'
import * as actions from './actions'
import getters from './getters'
const namespaced = true
export default {
    namespaced,
    actions,
    getters,
    mutations,
    state,
    root: true
}
        `.trim(),
      'utf8'
    )
  }
}
// 校验文件内是否已经存在
function _checkCorrect(filePath, regStr, apiUrl?: string) {
  // 1. 检查文件是否存在
  if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, '', 'utf8')
  }
  // 2. 读取文件内容
  const content = fs.readFileSync(filePath, 'utf8')

  // 3. 检查接口是否已存在
  const apiRegex = new RegExp(regStr, 'g')
  if (regStr && apiRegex.test(content)) {
    throw new Error(`已存在`)
  }

  // 4. 检查URL是否已存在
  if (apiUrl && content.includes(apiUrl)) {
    throw new Error(`接口地址 ${apiUrl} 已存在`)
  }
  return true
}
// 匹配是否满足条件的函数
function _checkFunctionExists(content, apiName) {
  // 匹配两种函数定义方式：
  // 1. export const fnName = ({ commit }) => {...}
  // 2. export function fnName({ commit }) {...}
  const funcRegex = new RegExp(
    `export\\s+(?:const\\s+${apiName}\\s*=\\\s*\\(|function\\s+${apiName}\\s*\\\()`
  )
  return funcRegex.test(content)
}
// 重新设置名称
function _firstUpperCase(str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}
/**
 *
 * @param {*} apiName  api名称
 * @param {*} apiUrl   api地址
 * @param {*} remark   api描述
 * @param {*} requestType   请求方式
 * @param {*} apiType  api类型['get', 'create', 'download', 'update', 'delete']
 * @returns
 */
export function initStoreFiles(dir: string, content: IStoreFilesParams) {
  BASE_DIR = dir + (content.fileName ? '/' + content.fileName : '')
  apiFilePath = `${BASE_DIR}/api.js`
  mutationsFilePath = `${BASE_DIR}/mutations.js`
  actionsFilePath = `${BASE_DIR}/actions.js`
  mutationTypesFilePath = `${BASE_DIR}/mutation-types.js`
  gettersFilePath = `${BASE_DIR}/getters.js`
  console.log(content.apiName, '===content.apiName', content.requestType)

  apiName = content.apiName
  remark = content.remark || ''
  apiUrl = content.apiUrl
  requestType = content.requestType || 'get'
  try {
    if (!fs.existsSync(BASE_DIR)) {
      fs.mkdirSync(BASE_DIR, { recursive: true })
    }
    // 1. 添加 API
    addApiToFile()
    // 2. 添加 addMutationTypes
    addMutationTypes()
    // 3. 添加 getters
    addGettersToFile()
    // 4. 添加 mutations
    addMutationsToFile()
    // 5. 添加 actions
    addActionsToFile()
    // 新建文件情况下
    if (content.fileName) {
      addIndexToFile()
    }
    return 'success'
  } catch (error: any) {
    console.error(error.message)
    return 'error'
  }
}
